<template>
  <div class="app-container">
    <div v-if="hasContent" style="margin-top: 0">
      <el-tooltip class="item" effect="dark" content="打开源网页" placement="bottom">
        <el-button
          style="right: 2%;margin-top: 1%;float: right; position:fixed;"
          type="primary"
          icon="el-icon-link"
          circle
          @click="onOpenOriginalWeb"
        />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="上一章" placement="bottom">
        <el-button
          v-if="index > 1"
          style="right: 2%;margin-top: 5%; float: right; position:fixed;"
          type="success"
          icon="el-icon-arrow-up"
          circle
          @click="getLastComicContent()"
        />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="打开章节目录" placement="bottom">
        <el-button
          v-if="comicDetailList && comicDetailList.length > 1"
          style="right: 2%;margin-top: 9%; float: right; position:fixed;"
          type="danger"
          icon="el-icon-more"
          circle
          @click="drawer = !drawer"
        />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="下一章" placement="bottom">
        <el-button
          v-if="index < comicDetailList.length"
          style="right: 2%;margin-top: 13%; float: right; position:fixed;"
          type="success"
          icon="el-icon-arrow-down"
          circle
          @click="getNextComicContent()"
        />
      </el-tooltip>
      <div style="float: left; position:fixed;text-align:center"><h4>第 {{ comicDetail.alt }} 话 [ {{ comicContent.length }}P ]</h4></div>
      <el-drawer
        direction="ttb"
        :visible.sync="drawer"
        :with-header="false"
      >
        <el-menu
          mode="horizontal"
          background-color="#545c64"
          text-color="#fff"
          @select="getComicContent"
        >
          <el-menu-item v-for="page in comicDetailList" :key="page.alt" style="width: 5%" :index="page.alt">
            <span slot="title">第 {{ page.alt }} 话</span>
          </el-menu-item>
        </el-menu>
      </el-drawer>
    </div>
    <el-container>
      <el-main style="margin-left: 15%; margin-right: 15%">
        <div id="original" ref="originalRef" style="width: 70%; text-align: center">
          <h4>{{ comic.alt }}</h4>
          <el-image
            v-for="content in comicContent"
            :id="'img-'+ content.sortNum"
            :key="content.comicContentId"
            :index="content.sortNum"
            :src="content.img"
            :alt="content.sortNum"
            lazy
            @load="load(content)"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import crudSpiderComicDetail from '@/api/spider/spiderComicDetail'
import crudSpiderWeb from '@/api/spider/spiderWeb'
import crudSpiderComicContent from '@/api/spider/spiderComicContent'
import md5 from 'js-md5'
import { setComicReadHistory, getComicReadHistory } from '@/utils/spiderUtil'

export default {
  name: 'SpiderComicDetail',
  data() {
    return {
      index: 1,
      hasContent: false,
      drawer: false,
      spiderWeb: {},
      targetCanvas: [],
      scramble_id: 220980,
      // first
      series_id: 0,
      // current
      aid: 0,
      comic: {},
      comicDetail: {},
      comicDetailList: [],
      comicContent: []
    }
  },
  created() {
    const params = this.$route.params
    this.hasContent = params && params.webId
    if (this.hasContent) {
      this.$loading()
      this.comic = params
      this.initPlay(params)
      this.getSpiderWeb(this.comic.webId)
      this.$loading().close()
    }
    if (!this.hasContent && this.comicContent.length === 0) {
      this.jumpToSelect()
    }
  },
  methods: {
    md5,
    jumpToSelect() {
      this.$message.error('请选择作品再阅读')
      this.$router.push({
        name: 'SpiderComic'
      })
    },
    load(content) {
      const dom = document.getElementById('img-' + content.sortNum)
      dom.parentNode.setAttribute('class', 'img')
      const imgName = this.getImgName(content)
      this.scramble_image(dom, this.aid, this.scramble_id, false, '', imgName)
    },
    initPlay(params) {
      const comicId = params.comicId
      const _this = this
      crudSpiderComicDetail.queryAllByComicId(comicId).then(res => {
        _this.comicDetailList = res
        _this.getComicContent(_this.getHistoryIndex())
        _this.series_id = _this.getOriginalComicId(_this.comicDetailList[0].href)
      })
    },
    getHistoryIndex() {
      const historyIndex = getComicReadHistory(this.comic.comicId)
      if (historyIndex) {
        this.index = historyIndex
      }
      setComicReadHistory(this.comic.comicId, this.index)
      return this.index
    },
    getLastComicContent() {
      this.index = parseInt(this.index)
      this.index -= 1
      this.getComicContent(this.index)
    },
    getNextComicContent() {
      this.index = parseInt(this.index)
      this.index += 1
      this.getComicContent(this.index)
    },
    getComicContent(index) {
      this.index = index
      // 设置阅读记录
      setComicReadHistory(this.comic.comicId, this.index)
      this.$loading()
      const _this = this
      const comicDetail = this.getComicDetailByIndex(index)
      _this.comicDetail = comicDetail
      _this.aid = _this.getOriginalComicId(comicDetail.href).replace('?', '')
      crudSpiderComicContent.queryAllByComicDetailId(comicDetail.comicDetailId).then(res => {
        _this.comicContent = res
        _this.$loading().close()
      })
    },
    getComicDetailByIndex(index) {
      return this.comicDetailList.filter(detail => detail.alt === index || detail.alt === index.toString())[0]
    },
    getOriginalComicId(path) {
      path.endsWith('/') ? path.substr(0, path.length - 1) : path
      const arr = path.split('/')
      return arr[arr.length - 1]
    },
    getSpiderWeb(webId) {
      const _this = this
      crudSpiderWeb.queryById(webId).then(res => {
        _this.spiderWeb = res
      })
    },
    onOpenOriginalWeb() {
      const originalPage = this.spiderWeb.domain + this.comicDetail.href
      window.open(originalPage, '_blank')
    },
    scramble_image(e, t, a, n, d, imgName) {
      n || (n = !1), d || (d = !1), e.src.indexOf('.gif') > 0 || parseInt(t) < parseInt(a) || d === '1' ? e.style.display === 'none' && (e.style.display = 'block') : n === 1 || e.complete === 0 ? document.getElementById(e.id)
        .onload = function() {
          this.onImageLoaded(e, imgName)
        } : this.onImageLoaded(e, imgName)
    },
    getImgName(content) {
      let imgName = parseInt(content.sortNum) + 1
      const len = 5 - imgName.toString().length
      for (let i = 0; i < len; i++) {
        imgName = '0' + imgName
      }
      return imgName
    },
    onImageLoaded(e, imgName) {
      let t
      e.nextElementSibling == null ? (t = document.createElement('canvas'), e.after(t)) : t = document.getElementById(e.id)
        .nextElementSibling
      const a = t.getContext('2d')
      let n = e.width
      const d = e.naturalWidth
      const i = e.naturalHeight
      t.width = d, t.height = i, (n > e.parentNode.offsetWidth || n === 0) && (n = e.parentNode.offsetWidth), t.style.width = n + 'px', t.style.display = 'block'
      let o = document.getElementById(e.id)
        .parentNode
      o = imgName
      for (let s = this.get_num(window.btoa(this.aid), window.btoa(o)), l = parseInt(i % s), r = d, m = 0; m < s; m++) {
        let c = Math.floor(i / s)
        let g = c * m
        const w = i - c * (m + 1) - l
        m === 0 ? c += l : g += l, a.drawImage(e, 0, w, r, c, 0, g, r, c)
      }
      e.remove()
    },
    get_num(e, t) {
      let a = 10
      let n = (e = window.atob(e)) + (t = window.atob(t))
      switch (n = (n = (n = md5(n))
        .substr(-1))
        .charCodeAt(), e >= window.atob('MjY4ODUw') && e <= window.atob('NDIxOTI1') ? n %= 10 : e >= window.atob('NDIxOTI2') && (n %= 8), n) {
        case 0:
          a = 2
          break
        case 1:
          a = 4
          break
        case 2:
          a = 6
          break
        case 3:
          a = 8
          break
        case 4:
          a = 10
          break
        case 5:
          a = 12
          break
        case 6:
          a = 14
          break
        case 7:
          a = 16
          break
        case 8:
          a = 18
          break
        case 9:
          a = 20
      }
      return a
    }
  }
}
</script>

<style scoped>
</style>
